#pragma once

#include <QtWidgets/QMainWindow>
#include <hv/TcpClient.h>
#include <hv/htime.h>
#include <hv/EventLoop.h>
#include <hv/EventLoopThread.h>

enum class cmd {
    INITCONNECT,            //初始化连接（cmd，name）
    DISCONNECT,
    HEARTBEAT,
    SEND,                   //转发消息（cmd，sender，receiver，content）
    SENDIMG,
    SENDPDFFILE
};


class QPushButton;
class QTextEdit;
class QLabel;
class QLineEdit;

class TClient : public QMainWindow
{
    Q_OBJECT

public:
    static TClient* Instance();
    TClient(QWidget *parent = nullptr);
    ~TClient();
    
    bool connection(int port, const char* host);
    void close();
    int cmdToInt(cmd command);

private:signals:
    void setCloseButtonEnables();
    void setStartButtonEnables();

private slots:
    void onSelectImgButtonReleased();
    void onSendImgButtonReleased();
    void onSendJsonPdfFile(std::string outputString);
private:
    void initUI();
    void initConnect();
    void Close();
    void sendInitInfo();
    std::string imageToString(const QString& filename);
    std::string sendHeartBeat();

    void setReconnect(reconn_setting_t* setting) {
        if (setting == NULL) {
            HV_FREE(reconn_setting);
            return;
        }
        if (reconn_setting == NULL) {
            HV_ALLOC_SIZEOF(reconn_setting);
        }
        *reconn_setting = *setting;
    }
    bool isReconnect() {
        return reconn_setting && reconn_setting->cur_retry_cnt > 0;
    }

    reconn_setting_t* reconn_setting;
    QPushButton* m_pStart;
    QPushButton* m_pEnd;

    QLabel* m_pHost;
    QLabel* m_pPort;
    QLabel* m_pName;

    QLineEdit* m_pHostLine;
    QLineEdit* m_pPortLine;
    QLineEdit* m_pNameLine;

    QTextEdit* m_pTextEdit;
    QPushButton* m_pSendButton;
    hv::TcpClient* m_pClient;

    QPushButton* m_pSelectImgButton;
    QPushButton* m_pSendImgButton;
    QString selectedImagePath;
    QString selectedImageName;
    QString selectedPdfFilePath;
    QString selectedPdfFileName;
    QPushButton* m_pUploadPdfFileButton;

    hv::EventLoopPtr m_HeartBeatLoop;
    hv::EventLoopThread m_HeartBeatLoopThread;
    int failedHeartBeat = 0;
};
